/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Class.Album;
import Class.process_XML;
import UIClass.ImageSelection;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import UIClass.imageHelper;
import java.awt.GraphicsDevice.*;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileNameExtensionFilter;


/**
 *
 * @author Paint
 */
class FileTreeCellRenderer extends DefaultTreeCellRenderer {

    private FileSystemView fileSystemView;
    private JLabel label;
    
    FileTreeCellRenderer() {
        label = new JLabel();
        label.setOpaque(true);
        fileSystemView = FileSystemView.getFileSystemView();
    }

    @Override
    public Component getTreeCellRendererComponent(
        JTree tree,
        Object value,
        boolean selected,
        boolean expanded,
        boolean leaf,
        int row,
        boolean hasFocus) {

        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        File file = (File)node.getUserObject();
        label.setIcon(fileSystemView.getSystemIcon(file));
        label.setText(fileSystemView.getSystemDisplayName(file));
        label.setToolTipText(file.getPath());

        if (selected) {
            label.setBackground(backgroundSelectionColor);
        } else {
            label.setBackground(backgroundNonSelectionColor);
        }

        return label;
    }
}
public class frmMain extends javax.swing.JFrame {
    /**
     * Creates new form frmMain
     */
    public frmMain() {
        initComponents();
    }
    JTree Otree;
    JTree OtreeAlbum;
    String IndexFolder;
    private ArrayList<File>lstImageForfolder;
    private ArrayList<File>lstImageForSearch;
    private int sttDislay;
    private static final String fileAlbum = "Album.xml";
    ArrayList<Album>arrAlbum;
    private Desktop desktop;
    private FileSystemView fileSystemView;
    private int imageChoosen;
    private int iSelectedAlbum=-1;
    private JPopupMenu PmenuforNormalImage;
    private JPopupMenu PmenuforAlbumImage;
    private JPopupMenu PmenuforTreeAlbumImage;
    private int indexRightClick;
    private boolean isRunnung=false;
    private int TotalSearched=0;
    private MouseListener emb;
    private MouseListener emf;
    private MouseListener ems;
    private JTextField txtRename;
    private File pathForCopy;
    private boolean isSelectedInContainer=false;
    private boolean isProcessSearch=false;
    private ArrayList<String> arrAlbumNameForSearch=new ArrayList();
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btnViewFiles = new org.jdesktop.swingx.JXButton();
        jSeparator15 = new javax.swing.JToolBar.Separator();
        jSeparator16 = new javax.swing.JToolBar.Separator();
        btnViewAlbum = new org.jdesktop.swingx.JXButton();
        jSeparator9 = new javax.swing.JToolBar.Separator();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnNewAlbum = new org.jdesktop.swingx.JXButton();
        jSeparator10 = new javax.swing.JToolBar.Separator();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        btnCaptureScreen = new javax.swing.JButton();
        jSeparator11 = new javax.swing.JToolBar.Separator();
        jSeparator12 = new javax.swing.JToolBar.Separator();
        jButton5 = new javax.swing.JButton();
        jSeparator14 = new javax.swing.JToolBar.Separator();
        jSeparator13 = new javax.swing.JToolBar.Separator();
        txtSearch = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        btnSearch = new org.jdesktop.swingx.JXButton();
        lbSearch = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        viewFolder = new javax.swing.JPanel();
        viewSearch = new javax.swing.JPanel();
        viewAlbum = new javax.swing.JPanel();
        lbStatusBar = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        menuCopy = new javax.swing.JMenuItem();
        menuCut = new javax.swing.JMenuItem();
        menuPaste = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        menuExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        menuNewAlbum = new javax.swing.JMenuItem();
        jMenu11 = new javax.swing.JMenu();
        menuAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Pikachu");
        setMinimumSize(new java.awt.Dimension(500, 500));
        setPreferredSize(new java.awt.Dimension(1350, 718));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jToolBar1.setRollover(true);

        btnViewFiles.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/ThuMuc_Phang.png"))); // NOI18N
        btnViewFiles.setFocusable(false);
        btnViewFiles.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnViewFiles.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnViewFiles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnViewFilesActionPerformed(evt);
            }
        });
        jToolBar1.add(btnViewFiles);
        jToolBar1.add(jSeparator15);
        jToolBar1.add(jSeparator16);

        btnViewAlbum.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/ThuMuc_Cay.png"))); // NOI18N
        btnViewAlbum.setFocusable(false);
        btnViewAlbum.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnViewAlbum.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnViewAlbum.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnViewAlbumActionPerformed(evt);
            }
        });
        jToolBar1.add(btnViewAlbum);
        jToolBar1.add(jSeparator9);
        jToolBar1.add(jSeparator1);

        btnNewAlbum.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Them_Album.png"))); // NOI18N
        btnNewAlbum.setFocusable(false);
        btnNewAlbum.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNewAlbum.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNewAlbum.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewAlbumActionPerformed(evt);
            }
        });
        jToolBar1.add(btnNewAlbum);
        jToolBar1.add(jSeparator10);
        jToolBar1.add(jSeparator3);

        btnCaptureScreen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Tai_Anh_Tu_ThietBi.png"))); // NOI18N
        btnCaptureScreen.setFocusable(false);
        btnCaptureScreen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCaptureScreen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCaptureScreen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCaptureScreenActionPerformed(evt);
            }
        });
        jToolBar1.add(btnCaptureScreen);
        jToolBar1.add(jSeparator11);
        jToolBar1.add(jSeparator12);

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Camera.png"))); // NOI18N
        jButton5.setFocusable(false);
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton5);
        jToolBar1.add(jSeparator14);
        jToolBar1.add(jSeparator13);

        txtSearch.setMaximumSize(new java.awt.Dimension(150, 2147483647));
        txtSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                txtSearchMouseEntered(evt);
            }
        });
        txtSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSearchKeyReleased(evt);
            }
        });
        jToolBar1.add(txtSearch);

        jButton2.setBorder(null);
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        btnSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/search.png"))); // NOI18N
        btnSearch.setFocusable(false);
        btnSearch.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSearch.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSearch);
        jToolBar1.add(lbSearch);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 255)));
        jPanel2.setPreferredSize(new java.awt.Dimension(1096, 600));

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 255)));
        jPanel3.setPreferredSize(new java.awt.Dimension(1096, 600));

        jScrollPane1.setMinimumSize(new java.awt.Dimension(200, 500));
        jSplitPane1.setLeftComponent(jScrollPane1);

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        viewFolder.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                viewFolderKeyPressed(evt);
            }
        });

        viewSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                viewSearchKeyPressed(evt);
            }
        });

        viewAlbum.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                viewAlbumKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout viewAlbumLayout = new javax.swing.GroupLayout(viewAlbum);
        viewAlbum.setLayout(viewAlbumLayout);
        viewAlbumLayout.setHorizontalGroup(
            viewAlbumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 838, Short.MAX_VALUE)
        );
        viewAlbumLayout.setVerticalGroup(
            viewAlbumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 574, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout viewSearchLayout = new javax.swing.GroupLayout(viewSearch);
        viewSearch.setLayout(viewSearchLayout);
        viewSearchLayout.setHorizontalGroup(
            viewSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(viewSearchLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(viewAlbum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(786, Short.MAX_VALUE))
        );
        viewSearchLayout.setVerticalGroup(
            viewSearchLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(viewSearchLayout.createSequentialGroup()
                .addComponent(viewAlbum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 92, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout viewFolderLayout = new javax.swing.GroupLayout(viewFolder);
        viewFolder.setLayout(viewFolderLayout);
        viewFolderLayout.setHorizontalGroup(
            viewFolderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(viewFolderLayout.createSequentialGroup()
                .addGap(844, 844, 844)
                .addComponent(viewSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(251, 251, 251))
        );
        viewFolderLayout.setVerticalGroup(
            viewFolderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(viewSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jScrollPane2.setViewportView(viewFolder);

        jSplitPane1.setRightComponent(jScrollPane2);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1346, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 647, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 1348, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 578, Short.MAX_VALUE)
        );

        lbStatusBar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        lbStatusBar.setText(" Thong bao");
        lbStatusBar.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(204, 204, 255), null));
        lbStatusBar.setPreferredSize(new java.awt.Dimension(66, 22));

        jMenu1.setText("File");

        menuCopy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        menuCopy.setText("Copy");
        menuCopy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCopyActionPerformed(evt);
            }
        });
        jMenu1.add(menuCopy);

        menuCut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        menuCut.setText("Cut");
        menuCut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCutActionPerformed(evt);
            }
        });
        jMenu1.add(menuCut);

        menuPaste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
        menuPaste.setText("Paste");
        menuPaste.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuPasteActionPerformed(evt);
            }
        });
        jMenu1.add(menuPaste);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
        jMenuItem2.setText("Delete");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        menuExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
        menuExit.setText("Exit");
        menuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuExitActionPerformed(evt);
            }
        });
        jMenu1.add(menuExit);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Album");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        menuNewAlbum.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        menuNewAlbum.setText("New Album");
        jMenu2.add(menuNewAlbum);

        jMenuBar1.add(jMenu2);

        jMenu11.setText("Help");

        menuAbout.setText("About us");
        menuAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuAboutActionPerformed(evt);
            }
        });
        jMenu11.add(menuAbout);

        jMenuBar1.add(jMenu11);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 1350, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbStatusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 1340, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 580, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                    .addComponent(lbStatusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    Image isImage(String filePath)
    {
        File file=new File(filePath);
        if(file.exists() && !file.isHidden() && file.canRead() && file.isFile())
        {
            try
            {
                BufferedImage buffer = ImageIO.read(file);
                //Image image = ImageIO.read(file);
                if(buffer.getWidth(null)!=-1)
                    return buffer;
            }
            catch(Exception ex)
            {
            
                return null;
            }
        }
        
        return null;
    }
    String checkExistImage(String path)
    {
        try
        {
        File folder=new File(path);
        if(folder.exists())
        {
            File[] listOfFiles = folder.listFiles();
            if(listOfFiles!=null)
            {
            for (File file : listOfFiles) 
            {
                if(!file.isHidden() && file.canRead() && file.length()>0 && file.canExecute())
                {
                    if (file.isFile())
                    {
                        //String mimeType = new MimetypesFileTypeMap().getContentType(file);
                        
                        Image image = new ImageIcon(file.getPath()).getImage();
                        if(image.getWidth(null)!=-1)
                            return file.getPath();
                        
                    }
                    else if(file.isDirectory() && file.getName().indexOf("$RECYCLE.BIN")<0)
                    {
                        String kq=checkExistImage(file.getPath());
                        if(kq!=null)
                            return kq;
                    }
                }
            }
            }
        }
        }
        catch(Exception ex)
        {
            System.out.println("disn chuong"+path);        
        }
        return null;
    }
    
    private void ResetMenuRightClick()
    {
        PmenuforAlbumImage = new JPopupMenu();
       
        JMenuItem menuItem;
        
        
        String pathToCopyImage = "images/edit_defaut_picture.png";
        ImageIcon ico2 = new ImageIcon(getClass().getClassLoader().getResource(pathToCopyImage));
        menuItem = new JMenuItem("Copy", ico2);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                File f ;
                if(!isProcessSearch)
                {
                    Album alb=arrAlbum.get(iSelectedAlbum);
                    f = new File(alb.getFiles().get(imageChoosen).toString());
                }
                else
                {
                    f = lstImageForSearch.get(imageChoosen);
                }
                if(f.exists())
                {
                    ImageIcon imgOriginal = new ImageIcon(f.getPath());
                    Image a = imgOriginal.getImage();

                    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                    ImageSelection selection = new ImageSelection(a);
                    clipboard.setContents(selection, null);
                    pathForCopy=f;
                }
                
            }
        });
        PmenuforAlbumImage.add(menuItem);
        
        
        String pathToDeleteImage = "images/BoAnhDuocChon.png";
        ImageIcon ico1 = new ImageIcon(getClass().getClassLoader().getResource(pathToDeleteImage));
        menuItem = new JMenuItem("Delete", ico1);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try{
                    String path="";
                    String pathAlbum=getClass().getResource(fileAlbum).getPath();
                    Album alb=arrAlbum.get(iSelectedAlbum);
                    if(!isProcessSearch)
                    {
                        path=alb.getFiles().get(imageChoosen).toString();
                        process_XML.RemoveImageXML(pathAlbum, alb.getName(), path);
                        alb.getFiles().remove(imageChoosen);
                        ResetImageForAlbum(alb);
                    }
                    else
                    {
                        File f = lstImageForSearch.get(imageChoosen);
                        path=f.getAbsolutePath();
                        process_XML.RemoveImageXML(pathAlbum, alb.getName(), path);
                        lstImageForSearch.remove(imageChoosen);
                        DeleteFile(viewSearch,lstImageForSearch,ems);
                    }
                    
                    
                
                
                TreePath selectedPath = OtreeAlbum.getSelectionPath() ;
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
                node.setUserObject(alb.getName()+" ("+alb.getFiles().size()+")");
 
            }catch(Exception ex){
 
    		ex.printStackTrace();
                
    	}
                
            }
        });
        PmenuforAlbumImage.add(menuItem);
        
         String pathToImageSortBy = "images/icon_search.png";
        ImageIcon ico = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
        menuItem = new JMenuItem("Local in Disk", ico);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                File f;
                if(!isProcessSearch)
                {
                    Album alb=arrAlbum.get(iSelectedAlbum);
                    f = new File(alb.getFiles().get(imageChoosen).toString());
                }
                else
                    f=lstImageForSearch.get(imageChoosen);
                if(f.exists())
                {
                    // path to the directory to be opened
                    try {
                    //desktop.open(folder);
                        Process p = new ProcessBuilder("explorer.exe", "/select,"+f.getPath()).start();
                    } 
                    catch (IOException ex) {
                    
                    }
                }

                
            }
        });
        PmenuforAlbumImage.add(menuItem);
        
        
        String pathToRename = "images/Refresh.png";
        ImageIcon icoRename = new ImageIcon(getClass().getClassLoader().getResource(pathToRename));
        JMenu menuRename = new JMenu("Rename to");
        menuRename.setIcon(icoRename);
        
        menuRename.add(txtRename);
       
        PmenuforAlbumImage.add(menuRename);
        
    }
    
    public void ResetImageForAlbum(Album abl)
    {
        int n=abl.getFiles().size();
                
        viewAlbum.removeAll();
        int totalRow=n/6;
        if(totalRow%6>0)
            totalRow++;
        int temp=(150*totalRow)+(totalRow-1)*25+50;
        viewAlbum.setPreferredSize(new Dimension(jSplitPane1.getRightComponent().getWidth(), temp));
        jScrollPane2.setViewportView(viewAlbum);
        JLabel label;
        int iRow,iCol;                          
        
        for(int j=0;j<n;j++)
        {
            String path=abl.getFiles().get(j).toString();
            File temp1=new File(path);
            if(!temp1.exists())
                path=getClass().getClassLoader().getResource("images/image_not_found.png").getPath();                  
            
            ImageIcon imgOriginal=new ImageIcon(path);
            label=new JLabel("");
            label.setSize(150, 150);
            label.setName(Integer.toString(j));
            ImageIcon ico= imageHelper.imageSize(imgOriginal, label);
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setIcon(ico);
            iRow=j/6;
            iCol=j%6;
            label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
            label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
            label.addMouseListener(emb);                  
            
            viewAlbum.add(label);                   
        }
        viewAlbum.repaint();                
    }
    void setAlbum(JTree tree, ArrayList<Album>alb)
    {
        TreeSelectionListener treeSelectionListener1 = new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent tse){
                int[] i=OtreeAlbum.getSelectionRows();
                if(i[0]!=0)
                {
                    isSelectedInContainer=false;
                    viewAlbum.setVisible(true);
                    viewSearch.setVisible(false);
                    isProcessSearch=false;
                    viewFolder.setVisible(false);
                    jScrollPane2.getViewport().add(viewAlbum);
            
                    Album abl=arrAlbum.get(i[0]-1);
                    ResetImageForAlbum(abl);
                    iSelectedAlbum=i[0]-1;
                    lbStatusBar.setText(abl.getFiles().size()+" files found");
                }
            }
        };
        DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Album", true);
        
        int n=alb.size();
        for(int i=0;i<n;i++)
        {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(alb.get(i).getName()+" ("+alb.get(i).getFiles().size()+")");
            parent.add(node);
        }
        OtreeAlbum = new JTree(parent);
        OtreeAlbum.setRootVisible(true);
        OtreeAlbum.addTreeSelectionListener(treeSelectionListener1);
        OtreeAlbum.expandRow(0);
    }
    public void ResetImageForFolder()
    {
        int count=lstImageForfolder.size();
            lbStatusBar.setText("Tìm được "+count + " file" );
            if(count>0)
            {
                viewFolder.removeAll();
                int totalRow=count/5;
                if(totalRow%5>0)
                    totalRow++;
                int temp=(150*totalRow)+(totalRow-1)*25+50;
                viewFolder.setPreferredSize(new Dimension(jSplitPane1.getRightComponent().getWidth(), temp));
                jScrollPane2.setViewportView(viewFolder);
                JLabel label;
                int iRow,iCol;
                
                for(int i=0;i<count;i++)
                {
                    ImageIcon imgOriginal=new ImageIcon(lstImageForfolder.get(i).getPath());
                    label=new JLabel("");
                    label.setSize(150, 150);
                    label.setName(Integer.toString(i));
                    ImageIcon ico= imageHelper.imageSize(imgOriginal, label);
                    label.setHorizontalAlignment(JLabel.CENTER);
                    label.setIcon(ico);
                    iRow=i/6;
                    iCol=i%6;
                    label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                    label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
                    label.addMouseListener(emf);
         
                    viewFolder.add(label);
                }
                viewFolder.repaint();
            }
    }
    void ResetView(int count,JPanel pn)
    {
        
        int totalRow=count/6;
        if(count%6>0)
            totalRow++;
        int temp=(150*(totalRow+2))+(totalRow-1)*25+50;
        
        pn.setPreferredSize(new Dimension(jSplitPane1.getRightComponent().getWidth(), temp));
        jScrollPane2.setViewportView(pn);
        pn.repaint();
    }
    
    public void addChildren(final DefaultMutableTreeNode node) {
        
        SwingWorker worker;
        worker = new SwingWorker() {
        @Override
        public String doInBackground() {
            Otree.setEnabled(false);
            
            //jProgressBar1.setVisible(true);
            jProgressBar1.setIndeterminate(true);
            File file = (File)node.getUserObject();
            if ( file.isDirectory() ) {
                IndexFolder=file.getPath();
                File[] files = fileSystemView.getFiles(file, true);
                if (node.isLeaf()) {
           
                    int n1=lstImageForfolder.size();
                    for(int i=0;i<n1;i++)
                        lstImageForfolder.remove(0);
                    
                    viewFolder.removeAll();
                    viewFolder.repaint();
                    for (File child : files) {
                        if(child.isDirectory() && checkExistImage(child.getPath())!=null)
                        {
                            node.add(new DefaultMutableTreeNode(child));
                        }
                        else
                        {
                         
                            Image img=isImage(child.getPath());
                            if(img!=null)
                            {
                                lstImageForfolder.add(child);
                                
                                int n=lstImageForfolder.size()-1;
                                
                                ImageIcon imgOriginal=new ImageIcon(img);
                                JLabel label=new JLabel("");
                                label.setSize(150, 150);
                                label.setName(Integer.toString(n));
                                ImageIcon ico= imageHelper.imageSize(imgOriginal, label);
                                
                                label.setHorizontalAlignment(JLabel.CENTER);
                                label.setIcon(ico);
                                int iRow=n/6;
                                int iCol=n%6;
                                label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                                label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
                                label.addMouseListener(emf);

                                viewFolder.add(label);
                                
                                if(iCol==0)
                                    ResetView(n,viewFolder);
                                else
                                    viewFolder.repaint();
                            }
                        }
                    }
            
                }
                else
                {
                    int n1=lstImageForfolder.size();
                    for(int i=0;i<n1;i++)
                        lstImageForfolder.remove(0);
                    viewFolder.removeAll();
                    for (File child : files) {
                        Image img=isImage(child.getPath());
                        if(img!=null)
                        {
                            
                            lstImageForfolder.add(child);
                            
                            int n=lstImageForfolder.size()-1;
                                
                                ImageIcon imgOriginal=new ImageIcon(child.getPath());
                                JLabel label=new JLabel("");
                                label.setSize(150, 150);
                                label.setName(Integer.toString(n));
                                ImageIcon ico= imageHelper.imageSize(imgOriginal, label);
                                label.setHorizontalAlignment(JLabel.CENTER);
                                label.setIcon(ico);
                                int iRow=n/6;
                                int iCol=n%6;
                                label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                                label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
                                label.addMouseListener(emf);

                                viewFolder.add(label);
                                
                                if(iCol==0)
                                    ResetView(n,viewFolder);
                                else
                                    viewFolder.repaint();
                            
                        }
                    }
                }
        
            }
            jProgressBar1.setIndeterminate(false);
            lbStatusBar.setText(lstImageForfolder.size()+"  files found");
            //jProgressBar1.setVisible(false);
            Otree.setEnabled(true);
        
            int[] i=Otree.getSelectionRows();
            Otree.expandRow(i[0]);
            jMenuBar1.setFocusable(true);
            return "done";
        }
        };
        worker.execute();
    }
    
    public void DeleteFile(final JPanel pn,final ArrayList<File>arr,final MouseListener m) {
        
        SwingWorker worker;
        worker = new SwingWorker() {
        @Override
        public String doInBackground() {
            
            jProgressBar1.setIndeterminate(true);
            pn.removeAll();
                        arr.remove(imageChoosen);
                        int n=arr.size();
                        JLabel label;
                        int iRow,iCol;
                        for(int i=0;i<n;i++)
                        {
                            ImageIcon imgOriginal=new ImageIcon(arr.get(i).getPath());
                            label=new JLabel("");
                            label.setSize(150, 150);
                            label.setName(Integer.toString(i));
                            ImageIcon ico= imageHelper.imageSize(imgOriginal, label);
                            label.setHorizontalAlignment(JLabel.CENTER);
                            label.setIcon(ico);
                            iRow=i/6;
                            iCol=i%6;
                            label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                            label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
                            label.addMouseListener(m);
                            pn.add(label);  
                        }
                        pn.repaint();
            jProgressBar1.setIndeterminate(false);
            
            return "done";
        }
        };
        worker.execute();
    }
    void ReloadPopupMenuForFolder()
    {
        
        PmenuforNormalImage = new JPopupMenu();
        String pathToAddAlbum = "images/right-icon.png";
        ImageIcon icoAddAlbum = new ImageIcon(getClass().getClassLoader().getResource(pathToAddAlbum));
        
        JMenu submenu = new JMenu("Add to album");
        submenu.setIcon(icoAddAlbum);
        
        JMenuItem menuItem;
                
        String pathAlbum=getClass().getResource(fileAlbum).getPath();
        arrAlbum=process_XML.getAlbums(pathAlbum);
        
        String pathIconAlbum = "images/folder_images.png";
        ImageIcon icoAlbum = new ImageIcon(getClass().getClassLoader().getResource(pathIconAlbum));
        int n=arrAlbum.size();
        
        for(int i=0;i<n;i++)
        {
            menuItem = new JMenuItem(arrAlbum.get(i).getName(),icoAlbum);
            menuItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                       
                        JMenuItem te=(JMenuItem)e.getSource();
                        String pathAlbum=getClass().getResource(fileAlbum).getPath();
                        if(!isProcessSearch)
                            process_XML.AddImageXML(pathAlbum,te.getText(),lstImageForfolder.get(indexRightClick).getPath());
                        else
                            process_XML.AddImageXML(pathAlbum,te.getText(),lstImageForSearch.get(indexRightClick).getPath());
                        
                    }
        });
            submenu.add(menuItem);
        }
        
        
        submenu.addSeparator();
        String pathToNewAlbum = "images/star.png";
        ImageIcon icoNewAlbum = new ImageIcon(getClass().getClassLoader().getResource(pathToNewAlbum));
        menuItem = new JMenuItem("New album", icoNewAlbum); 
        
        submenu.add(menuItem);

                    menuItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                       
                        
                        ArrayList<String>arr=new ArrayList<String>();
                        if(!isProcessSearch)
                            arr.add(lstImageForfolder.get(indexRightClick).getPath());
                        else
                            arr.add(lstImageForSearch.get(indexRightClick).getPath());
                        
                        Album abl=new Album("", "", "", "", arr);
                        NewAlbum na=new NewAlbum(frmMain.this, true, abl);
                        na.setVisible(true);
                        if(!na.getIsClose())
                        {
                            arrAlbum.add(abl);
                            if(sttDislay==2)
                            {
                                DefaultTreeModel model = (DefaultTreeModel) OtreeAlbum.getModel();
                                DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
                                model.insertNodeInto(new DefaultMutableTreeNode(abl.getName()+" ("+abl.getFiles().size()+")"), root, root.getChildCount());
                            }
                            ReloadPopupMenuForFolder();
                            JOptionPane.showMessageDialog(null,"Tạo album thành công");
                        }
                    }
        });
        PmenuforNormalImage.add(submenu);
        
        String pathToDelete = "images/BoAnhDuocChon.png";
        ImageIcon icoDelete = new ImageIcon(getClass().getClassLoader().getResource(pathToDelete));
        menuItem = new JMenuItem("Delete", icoDelete);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try{
 
    		File f;
                    if(!isProcessSearch)
                        f = lstImageForfolder.get(imageChoosen);
                    else
                        f = lstImageForSearch.get(imageChoosen);
 
    		if(f.delete()){
                    if(!isProcessSearch)
                    {
                        DeleteFile(viewFolder, lstImageForfolder,emf);
                    }
                    else
                    {
                         DeleteFile(viewSearch, lstImageForSearch,ems);
                    }
                }
                else{
    			System.out.println("Delete operation is failed.");
    		}
 
            }catch(Exception ex){
                System.out.println(ex.getMessage());
    	}
                
            }
        });
        PmenuforNormalImage.add(menuItem);
        
        String pathToCopy = "images/edit_defaut_picture.png";
        ImageIcon icoCopy = new ImageIcon(getClass().getClassLoader().getResource(pathToCopy));
        menuItem = new JMenuItem("Copy", icoCopy);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                    File f;
                    if(!isProcessSearch)
                        f = lstImageForfolder.get(imageChoosen);
                    else
                        f = lstImageForSearch.get(imageChoosen);
                        
                    ImageIcon imgOriginal = new ImageIcon(f.getPath());
                    Image a = imgOriginal.getImage();

                    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                    ImageSelection selection = new ImageSelection(a);
                    clipboard.setContents(selection, null);
                    pathForCopy=f;     
                    
                
            }
        });
        PmenuforNormalImage.add(menuItem);
        
        
        String pathToCopyTo = "images/Exit.png";
        ImageIcon icoCopyTo = new ImageIcon(getClass().getClassLoader().getResource(pathToCopyTo));
        menuItem = new JMenuItem("Copy to", icoCopyTo);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                File f;
                if(!isProcessSearch)
                    f = lstImageForfolder.get(imageChoosen);
                else
                    f = lstImageForSearch.get(imageChoosen);
                JFileChooser saveFile = new JFileChooser();
                saveFile.setAcceptAllFileFilterUsed(false);
                saveFile.addChoosableFileFilter(new FileNameExtensionFilter(".jpg", "jpg"));
                saveFile.addChoosableFileFilter(new FileNameExtensionFilter(".jpeg", "jpeg"));
                saveFile.addChoosableFileFilter(new FileNameExtensionFilter(".png", "png"));
                saveFile.setSelectedFile(f);
                saveFile.setName("Copy to");
                //saveFile.set
                int returnVal =saveFile.showSaveDialog(null);
                
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = saveFile.getSelectedFile();
                    if(file.exists())
                        JOptionPane.showMessageDialog(null,"File đã tồn tại trong trong thư mục hiện tại");
                    else
                    {
                        String path=f.getAbsolutePath();
                        Image image = new ImageIcon(path).getImage();
                        BufferedImage bi = imageHelper.toBufferedImage(image);
                        
                        int index1=path.lastIndexOf(".");
                        String eFile=path.substring(index1+1,path.length());
                        try {
                            ImageIO.write(bi, eFile, file);
                        } catch (IOException ex) {
                            Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    
            
                    }
                        
                }
 
            }
        });
        PmenuforNormalImage.add(menuItem);
        
        String pathToLocal = "images/picture_zoom.png";
        ImageIcon icoLocal = new ImageIcon(getClass().getClassLoader().getResource(pathToLocal));
        menuItem = new JMenuItem("Local in Disk", icoLocal);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                File f;
                if(!isProcessSearch)
                    f = lstImageForfolder.get(imageChoosen);
                else
                    f = lstImageForSearch.get(imageChoosen);
                if(f.exists())
                {
                    // path to the directory to be opened
                    try {
                    //desktop.open(folder);
                        Process p = new ProcessBuilder("explorer.exe", "/select,"+f.getPath()).start();
                    } 
                    catch (IOException ex) {
                    
                    }
                }

            }
        });
        PmenuforNormalImage.add(menuItem);
        
        String pathToRename = "images/Refresh.png";
        ImageIcon icoRename = new ImageIcon(getClass().getClassLoader().getResource(pathToRename));
        JMenu menuRename = new JMenu("Rename to");
        menuRename.setIcon(icoRename);
        
        menuRename.add(txtRename);
        
        PmenuforNormalImage.add(menuRename);
    }
    
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        this.setLocationRelativeTo(null);
        sttDislay=1;
        fileSystemView = FileSystemView.getFileSystemView();
        txtRename = new JTextField("",20);
        txtRename.addKeyListener(new java.awt.event.KeyAdapter() {
            @Override
            public void keyPressed(java.awt.event.KeyEvent evt) {
                if(evt.getKeyCode() == KeyEvent.VK_ENTER){
                    if(sttDislay==1)
                    {
                        File oldfile;
                        if(!isProcessSearch)
                            oldfile = lstImageForfolder.get(imageChoosen);
                        else
                            oldfile = lstImageForSearch.get(imageChoosen);
                        if(oldfile.exists())
                        {
                            String strName=oldfile.getAbsolutePath();
                            int index=strName.lastIndexOf("\\");
                            int index1=strName.lastIndexOf(".");
                            String eFile=strName.substring(index1,strName.length());
                            String Newpath=oldfile.getAbsolutePath().substring(0,index)+"\\"+txtRename.getText()+eFile;
                    
                            File newfile =new File(Newpath);
                            if(newfile.exists())
                                JOptionPane.showMessageDialog(null,"Tên file đã tồn tại");
                            else
                            {
                                if(oldfile.renameTo(newfile)){
                                    PmenuforNormalImage.setVisible(false);
                                    txtRename.setText(newfile.getName());
                                    System.out.println("Rename succesful");
                                    if(!isProcessSearch)
                                        lstImageForfolder.set(imageChoosen, newfile);
                                    else
                                        lstImageForSearch.set(imageChoosen, newfile);
                                    
                                    lbStatusBar.setText(Newpath);
                                    
                                }else{
                                    PmenuforNormalImage.setVisible(false);
                                    System.out.println("Rename failed");
                                }
                            }
                        }
                    }
                    else
                    {
                        File oldFile;
                        String strFile="";
                        Album abl=new Album();
                        if(!isProcessSearch)
                        {
                            int []i=OtreeAlbum.getSelectionRows();
                            if(i[0]>0)
                            {
                                abl=arrAlbum.get(i[0]-1);
                                strFile=(String)abl.getFiles().get(imageChoosen);
                                oldFile=new File(strFile);
                            }
                            else
                                return;
                        }
                        else
                        {
                            oldFile=lstImageForSearch.get(imageChoosen);
                            strFile=oldFile.getAbsolutePath();
                        }
                        if(oldFile.exists())
                            {
                                int index=strFile.lastIndexOf("\\");
                                int index1=strFile.lastIndexOf(".");
                                String eFile=strFile.substring(index1,strFile.length());
                                String Newpath=strFile.substring(0,index)+"\\"+txtRename.getText()+eFile;
                    
                                File newfile =new File(Newpath);
                                if(newfile.exists())
                                    JOptionPane.showMessageDialog(null,"Tên file đã tồn tại");
                                else
                                {
                                    if(oldFile.renameTo(newfile)){
                                        PmenuforAlbumImage.setVisible(false);
                                        txtRename.setText(newfile.getName());
                                        System.out.println("Rename succesful");
                                        String ablName="";
                                        if(!isProcessSearch)
                                        {
                                            abl.getFiles().set(imageChoosen,Newpath);
                                            ablName=abl.getName();
                                            
                                        }
                                        else
                                        {
                                            ablName=arrAlbumNameForSearch.get(imageChoosen);
                                            int nA=arrAlbum.size();
                                            for(int i=0;i<nA;i++)
                                            {
                                                if(arrAlbum.get(i).getName().equalsIgnoreCase(ablName))
                                                {
                                                    abl=arrAlbum.get(i);
                                                    abl.getFiles().set(imageChoosen,Newpath);
                                                    break;
                                                }
                                                
                                            }
                                            
                                        }
                                        String pathAlbum=getClass().getResource(fileAlbum).getPath();
                                        process_XML.RenameImageXML(pathAlbum,ablName,strFile,Newpath);
                                        lbStatusBar.setText(Newpath);
                                    
                                    }else{
                                        PmenuforNormalImage.setVisible(false);
                                        System.out.println("Rename failed");
                                    }
                                }
                            }
                        }
                    
                    
                }
            }
            
        });
        
        desktop = Desktop.getDesktop();
        
        lstImageForfolder=new ArrayList();
        lstImageForSearch=new ArrayList();
        
        
        DefaultMutableTreeNode root = new DefaultMutableTreeNode();

        File[] roots = fileSystemView.getRoots();
        for(File fileSystemRoot : roots) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileSystemRoot);
            root.add( node );
            File[] files = fileSystemView.getFiles(fileSystemRoot, true);
            boolean isMycomputer=true;
            for (File file : files) {
                if(file.isDirectory() && (isMycomputer==true || checkExistImage(file.getPath())!=null))
                {
                    node.add(new DefaultMutableTreeNode(file));
                    isMycomputer=false;
                }
            }
        }
            
        TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent tse){
                isSelectedInContainer=false;
                viewAlbum.setVisible(false);
                viewSearch.setVisible(false);
                isProcessSearch=false;
                viewFolder.setVisible(true);
                jScrollPane2.getViewport().add(viewFolder);
                
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)tse.getPath().getLastPathComponent();
                addChildren(node);
                txtSearch.setFocusable(false);
            }
        };
            
        Otree = new JTree(root);
        Otree.setRootVisible(false);
        Otree.addTreeSelectionListener(treeSelectionListener);
        Otree.setCellRenderer(new FileTreeCellRenderer());
        Otree.expandRow(0);
        jScrollPane1.getViewport().add(Otree);
        
        ReloadPopupMenuForFolder();
        
        JMenuItem menuItem;
         
        String pathToEditInfoImage = "images/Refresh.png";
        ImageIcon EditInfoico = new ImageIcon(getClass().getClassLoader().getResource(pathToEditInfoImage));        
        PmenuforTreeAlbumImage=new JPopupMenu();
        menuItem = new JMenuItem("Edit info", EditInfoico);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int k=OtreeAlbum.getSelectionRows()[0];
                NewAlbum na=new NewAlbum(frmMain.this, true,arrAlbum.get(k-1));
                na.setVisible(true);
                
                if(na.getIsClose()==false)
                {
                    TreePath selectedPath = OtreeAlbum.getSelectionPath() ;
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
                    node.setUserObject(arrAlbum.get(k-1).getName()+" ("+arrAlbum.get(k-1).getFiles().size()+")");
                }
            }
        });
        PmenuforTreeAlbumImage.add(menuItem);
        
        String pathToDeleteImage = "images/BoAnhDuocChon.png";
        ImageIcon Deleteico = new ImageIcon(getClass().getClassLoader().getResource(pathToDeleteImage));
        menuItem = new JMenuItem("Delete", Deleteico);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int k=OtreeAlbum.getSelectionRows()[0];
                                if(k>=0)
                                {
                                    int selectedOption = JOptionPane.showConfirmDialog(null, 
                                  "Xóa tất cả ảnh trong album hiện tại?", 
                                  "Xác nhận", 
                                  JOptionPane.YES_NO_OPTION); 
                                    if (selectedOption == JOptionPane.YES_OPTION) {
                                            //String albumName=arrAlbum.get(k-1).getName();
                                        String pathAlbum=getClass().getResource(fileAlbum).getPath();
                                            process_XML.RemoveAlbumXML(pathAlbum, arrAlbum.get(k-1).getName());
                                            arrAlbum.remove(k-1);
                                            
                                            setAlbum(OtreeAlbum,arrAlbum);
                                            ReloadPopupMenuForFolder();
                                            OtreeAlbum.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent ke) {  // handler
                            if(ke.getKeyCode() == KeyEvent.VK_DELETE)
                            {
                                //ResetPanel(imageChoosen);
                                int k=OtreeAlbum.getSelectionRows()[0];
                                if(k>=0)
                                {
                                    int selectedOption = JOptionPane.showConfirmDialog(null, 
                                  "Xóa tất cả ảnh trong album hiện tại?", 
                                  "Xác nhận", 
                                  JOptionPane.YES_NO_OPTION); 
                                    if (selectedOption == JOptionPane.YES_OPTION) {
                                            //String albumName=arrAlbum.get(k-1).getName();
                                        String pathAlbum=getClass().getResource(fileAlbum).getPath();
                                            process_XML.RemoveAlbumXML(pathAlbum, arrAlbum.get(k-1).getName());
                                            arrAlbum.remove(k-1);
                                            //OtreeAlbum.remove(k);
                                            //OtreeAlbum.remove(k);
                                            setAlbum(OtreeAlbum,arrAlbum);
                                            jScrollPane1.getViewport().add(OtreeAlbum);
                                        
                                        }
                                }
                            }
                        }
                    });
            MouseListener mt=new MouseListener()
                    {
                        
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            
                            
                        }
                        @Override
                        public void mouseEntered(MouseEvent arg0) {
                        }
                        @Override
                        public void mouseExited(MouseEvent arg0) {
                        }
                        @Override
                        public void mousePressed(MouseEvent arg0) {
                        }
                        @Override
                        public void mouseReleased(MouseEvent arg0) {
                            if(OtreeAlbum.getSelectionCount()>0 && SwingUtilities.isRightMouseButton(arg0)){
                                if (arg0.isPopupTrigger()) 
                                    PmenuforTreeAlbumImage.show(arg0.getComponent(), arg0.getX(), arg0.getY());
                            }
                        }
                        
                    };
            OtreeAlbum.addMouseListener(mt);
                                            jScrollPane1.getViewport().add(OtreeAlbum);
                                        
                                        }
                                }
            }
        });
        PmenuforTreeAlbumImage.add(menuItem);
        
        emb=new MouseListener()
        {
            @Override
            public void mouseClicked(MouseEvent e) {                            
            }
            @Override
            public void mouseEntered(MouseEvent arg0) {
            }
            @Override
            public void mouseExited(MouseEvent arg0) {
            }
            @Override
            public void mousePressed(MouseEvent e) {
                if(e.getClickCount()==1)
                {
                    Component c = null;
                    Component[] components = viewAlbum.getComponents();
                    if(components != null)
                    {
                        int numComponents = components.length;
                        for(int i = 0; i < numComponents; i++)
                        {
                            c = components[i];
                            if(c != null)
                            {
                                if(c instanceof JLabel)
                                {
                                    JLabel lb=(JLabel)c;
                                    lb.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                                }
                            }
                        }
                    }
                    JLabel lb=(JLabel)e.getSource();
                    lb.setBorder(BorderFactory.createLineBorder(Color.BLUE,2));
                    imageChoosen=Integer.parseInt(lb.getName());
                    int[] i=OtreeAlbum.getSelectionRows();                                            
                    
                    Album abl=arrAlbum.get(i[0]-1);
                    ArrayList<String>arrTemp=abl.getFiles();
                    String strPath=arrTemp.get(imageChoosen);
                    File f=new File(strPath);
                    lbStatusBar.setText(" "+f.getAbsolutePath());
                    int index=f.getName().lastIndexOf(".");
                    txtRename.setText(f.getName().substring(0,index));
                }
                else if(e.getClickCount()==2)
                {                                         
                    int[] i=OtreeAlbum.getSelectionRows();                                            
                    if(i[0]!=0)
                    {
                        Album abl=arrAlbum.get(i[0]-1);
                        ArrayList<File>arrFile=new ArrayList<File>();
                        for(int j=0;j<abl.getFiles().size();j++)
                        {
                            File f=new File(abl.getFiles().get(j).toString());
                            if(f.exists())
                                arrFile.add(f);
                        }
                        if(arrFile.size()>0)
                        {
                            OpenViewPhoto(arrFile,arrFile.size()/2);
                        }
                    }
                }
            }
            @Override
            public void mouseReleased(MouseEvent arg0) {
                if (arg0.isPopupTrigger()  && SwingUtilities.isRightMouseButton(arg0)) {
                    ResetMenuRightClick();
                    
                    
                    PmenuforAlbumImage.show(arg0.getComponent(), arg0.getX(), arg0.getY());
                }
            }                                
        };
        
        emf=new MouseListener()
        {
            @Override
            public void mouseClicked(MouseEvent e) {
            }
            @Override
            public void mouseEntered(MouseEvent arg0) {
            }
            @Override
            public void mouseExited(MouseEvent arg0) {
            }
            @Override
            public void mousePressed(MouseEvent e) {
                if(e.getClickCount()==1)
                {
                    Component c = null;
                    Component[] components = viewFolder.getComponents();                  
                    if(components != null)
                    {
                        int numComponents = components.length;
                        for(int i = 0; i < numComponents; i++)
                        {
                            c = components[i];
                            if(c != null)
                            {
                                if(c instanceof JLabel)
                                {
                                    JLabel lb=(JLabel)c;
                                    lb.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                                }
                            }
                        }
                    }
                    JLabel lb=(JLabel)e.getSource();
                    lb.setBorder(BorderFactory.createLineBorder(Color.BLUE,2));
                    imageChoosen=Integer.parseInt(lb.getName());
                    isSelectedInContainer=true;
                    lbStatusBar.setText(" "+lstImageForfolder.get(Integer.parseInt(lb.getName())));
                    
                    String strName=lstImageForfolder.get(Integer.parseInt(lb.getName())).getName();
                    int index=strName.lastIndexOf(".");
                    txtRename.setText(strName.substring(0,index));
                    
                   
                }
                else if(e.getClickCount()==2)
                {
                    JLabel lb=(JLabel)e.getSource();
                    OpenViewPhoto(lstImageForfolder, Integer.parseInt(lb.getName()));
                }
            }
            @Override
            public void mouseReleased(MouseEvent arg0) {
                if (arg0.isPopupTrigger()  && SwingUtilities.isRightMouseButton(arg0)) {
                    JLabel lb=(JLabel)arg0.getSource();
                    indexRightClick= Integer.parseInt(lb.getName());
                   
                    PmenuforNormalImage.show(arg0.getComponent(), arg0.getX(), arg0.getY());
                }
            }                    
        };
        
        ems=new MouseListener()
        {
            @Override
            public void mouseClicked(MouseEvent e) {
            }
            @Override
            public void mouseEntered(MouseEvent arg0) {
            }
            @Override
            public void mouseExited(MouseEvent arg0) {
            }
            @Override
            public void mousePressed(MouseEvent e) {
                if(e.getClickCount()==1)
                {
                    Component c = null;
                    Component[] components = viewFolder.getComponents();                  
                    if(components != null)
                    {
                        int numComponents = components.length;
                        for(int i = 0; i < numComponents; i++)
                        {
                            c = components[i];
                            if(c != null)
                            {
                                if(c instanceof JLabel)
                                {
                                    JLabel lb=(JLabel)c;
                                    lb.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                                }
                            }
                        }
                    }
                    JLabel lb=(JLabel)e.getSource();
                    lb.setBorder(BorderFactory.createLineBorder(Color.BLUE,2));
                    imageChoosen=Integer.parseInt(lb.getName());
                    isSelectedInContainer=true;
                    lbStatusBar.setText(" "+lstImageForSearch.get(Integer.parseInt(lb.getName())));
                    String strName=lstImageForSearch.get(Integer.parseInt(lb.getName())).getName();
                    int index=strName.lastIndexOf(".");
                    txtRename.setText(strName.substring(0,index));
                    
                }
                else if(e.getClickCount()==2)
                {
                    JLabel lb=(JLabel)e.getSource();
                    OpenViewPhoto(lstImageForSearch, Integer.parseInt(lb.getName()));
                }
            }
            @Override
            public void mouseReleased(MouseEvent arg0) {
                if (arg0.isPopupTrigger()  && SwingUtilities.isRightMouseButton(arg0)) {
                    if(sttDislay==1)
                    {
                        JLabel lb=(JLabel)arg0.getSource();
                        indexRightClick= Integer.parseInt(lb.getName());
                        PmenuforNormalImage.show(arg0.getComponent(), arg0.getX(), arg0.getY());
                    }
                    else
                    {
                        ResetMenuRightClick();
                        PmenuforAlbumImage.show(arg0.getComponent(), arg0.getX(), arg0.getY());
                    }
                    
                }
            }                    
        };
    }//GEN-LAST:event_formWindowOpened
    
    private void OpenViewPhoto(final ArrayList<File>arr,final int index)
    {
        SwingWorker worker;
        worker = new SwingWorker() {
        @Override
        public String doInBackground() {
            jProgressBar1.setIndeterminate(true);
            ViewPhotos f=new ViewPhotos( frmMain.this, true,arr,index);
            f.setVisible(true);
            jProgressBar1.setIndeterminate(false);
            return "done";
        }
        };
        worker.execute();
    }
    
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed
    
    private void btnViewFilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewFilesActionPerformed
        // TODO add your handling code here:
        if(sttDislay==2)
        {
            viewAlbum.setVisible(false);
            viewSearch.setVisible(false);
            isProcessSearch=false;
            viewFolder.setVisible(true);
            
            OtreeAlbum.setVisible(false);
            Otree.setVisible(true);
            jScrollPane1.getViewport().add(Otree);
            jScrollPane2.getViewport().add(viewFolder);
            sttDislay=1;
        }
    }//GEN-LAST:event_btnViewFilesActionPerformed

    private void btnViewAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewAlbumActionPerformed
        // TODO add your handling code here:'
        if(sttDislay==1)
        {
            viewAlbum.setVisible(true);
            viewSearch.setVisible(false);
            isProcessSearch=false;
            viewFolder.setVisible(false);
            
            String pathAlbum=getClass().getResource(fileAlbum).getPath();
            arrAlbum=process_XML.getAlbums(pathAlbum);
            
            setAlbum(OtreeAlbum,arrAlbum);
            if(arrAlbum.size()>0 && iSelectedAlbum>=0)
            {
                OtreeAlbum.setSelectionRow(iSelectedAlbum+1);
            }
            
            Otree.setVisible(false);
            OtreeAlbum.setVisible(true);
            OtreeAlbum.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent ke) {  // handler
                            if(ke.getKeyCode() == KeyEvent.VK_DELETE)
                            {
                                //ResetPanel(imageChoosen);
                                int k=OtreeAlbum.getSelectionRows()[0];
                                if(k>=0)
                                {
                                    int selectedOption = JOptionPane.showConfirmDialog(null, 
                                  "Xóa tất cả ảnh trong album hiện tại?", 
                                  "Xác nhận", 
                                  JOptionPane.YES_NO_OPTION); 
                                    if (selectedOption == JOptionPane.YES_OPTION) {
                                            //String albumName=arrAlbum.get(k-1).getName();
                                        String pathAlbum=getClass().getResource(fileAlbum).getPath();
                                            process_XML.RemoveAlbumXML(pathAlbum, arrAlbum.get(k-1).getName());
                                            arrAlbum.remove(k-1);
                                            //OtreeAlbum.remove(k);
                                            //OtreeAlbum.remove(k);
                                            setAlbum(OtreeAlbum,arrAlbum);
                                            jScrollPane1.getViewport().add(OtreeAlbum);
                                        
                                        }
                                }
                            }
                        }
                    });
            MouseListener mt=new MouseListener()
                    {
                        
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            
                            
                        }
                        @Override
                        public void mouseEntered(MouseEvent arg0) {
                        }
                        @Override
                        public void mouseExited(MouseEvent arg0) {
                        }
                        @Override
                        public void mousePressed(MouseEvent arg0) {
                        }
                        @Override
                        public void mouseReleased(MouseEvent arg0) {
                            if(OtreeAlbum.getSelectionCount()>0 && SwingUtilities.isRightMouseButton(arg0)){
                                if (arg0.isPopupTrigger()) 
                                    PmenuforTreeAlbumImage.show(arg0.getComponent(), arg0.getX(), arg0.getY());
                            }
                        }
                        
                    };
            OtreeAlbum.addMouseListener(mt);
            
            jScrollPane1.getViewport().add(OtreeAlbum);
            sttDislay=2;
            
            
        }
        
    }//GEN-LAST:event_btnViewAlbumActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton5ActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        if(isRunnung)
        {
            String pathToImageSortBy = "images/Search.png";
            ImageIcon ico = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
            btnSearch.setIcon(ico);
            isRunnung=false;
            txtSearch.setEditable(true);
            txtSearch.setFocusable(true);
            
        }
        else
        {
            if(txtSearch.getText().equals(""))
                return;
            isRunnung=true;
            String pathToImageSortBy = "images/BoAnhDuocChon.png";
            ImageIcon ico = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
            btnSearch.setIcon(ico);
            txtSearch.setEditable(false);
            txtSearch.setFocusable(false);
            isSelectedInContainer=false;
            if(sttDislay==1)
                actionSearch_Folder();
            else
                actionSearch_Album(txtSearch.getText());
            lbStatusBar.setText(TotalSearched+"  files found");
        }
    }//GEN-LAST:event_btnSearchActionPerformed

    private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSearchKeyReleased
        // TODO add your handling code here:
        if(evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)
        {
          
            if(txtSearch.getText().equals(""))
            {
                lbSearch.setText("");
                viewSearch.setVisible(false);
                isProcessSearch=false;
                if(sttDislay==1)
                {
                    
                    viewFolder.setVisible(true);
                    jScrollPane2.getViewport().add(viewFolder);
                    viewAlbum.setVisible(false);
                }
                else
                {
                    viewFolder.setVisible(false);
                    viewAlbum.setVisible(true);
                    jScrollPane2.getViewport().add(viewAlbum);
                }
            }
            
        }
    }//GEN-LAST:event_txtSearchKeyReleased

    private void btnNewAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewAlbumActionPerformed
        // TODO add your handling code here:
        ArrayList<String> arr=new ArrayList<String>();
        Album abl=new Album("", "", "", "", arr);
        NewAlbum na=new NewAlbum(this, true, abl);
        na.setVisible(true);
        if(!na.getIsClose())
        {
            arrAlbum.add(abl);
            ReloadPopupMenuForFolder();
            DefaultTreeModel model = (DefaultTreeModel) OtreeAlbum.getModel();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
            model.insertNodeInto(new DefaultMutableTreeNode(abl.getName()+" ("+abl.getFiles().size()+")"), root, root.getChildCount());
        }
    }//GEN-LAST:event_btnNewAlbumActionPerformed

    private void btnCaptureScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCaptureScreenActionPerformed
        // TODO add your handling code here:
        Robot robot;
        try {
                robot = new Robot();
                BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
                Date d=new Date();
                File f=new File("screenShot_"+d.getTime()+".jpg");
                ImageIO.write(screenShot, "JPG",f);
                String pathAlbum=getClass().getResource(fileAlbum).getPath();
                int n=arrAlbum.size();
                int i=0;
                for(;i<n;i++)
                    if(arrAlbum.get(i).getName().equals("ScreenShot"))
                        break;
                if(i==n)
                {
                    Album alb=new Album();
                    
                    alb.setName("ScreenShot");
                    SimpleDateFormat fd = new SimpleDateFormat("MM/dd/yyyy");
                    String NS=fd.format(d);
                    alb.setDate(NS);
                    alb.setDescription("Capture screenshot");
                    alb.setTitle("Capture screenshot");
                    ArrayList<String>arrFile=new ArrayList();
                    arrFile.add(f.getAbsolutePath());
                    alb.setFiles(arrFile);
                    process_XML.AddAlbumXML(pathAlbum,alb);
                    arrAlbum.add(alb);
                   
                    
                    if(sttDislay==2 )
                    {
                        DefaultTreeModel model = (DefaultTreeModel) OtreeAlbum.getModel();
                        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
                        model.insertNodeInto(new DefaultMutableTreeNode("ScreenShot (1)"), root, root.getChildCount());
                        
                    }
                }
                else
                {
                    process_XML.AddImageXML(pathAlbum, "ScreenShot", f.getPath());
                    Album al=arrAlbum.get(i);
                    ArrayList<String>arrFile=al.getFiles();
                    arrFile.add(f.getAbsolutePath());
                    al.setFiles(arrFile);
                    arrAlbum.set(i, al);
                    
                    TreePath selectedPath = OtreeAlbum.getPathForRow(i+1);
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
                    String str=al.getName()+" ("+al.getFiles().size()+")";
                    node.setUserObject(str);
                    if(sttDislay==2 )
                    {
                        OtreeAlbum.repaint();
                        if(OtreeAlbum.getSelectionRows()[0]==i+1)
                            ResetImageForAlbum(al);
                    }
                    
                }
                
            }
            catch (Exception ex) {
            Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
        }
 
		
    }//GEN-LAST:event_btnCaptureScreenActionPerformed

    private void menuCopyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCopyActionPerformed
        // TODO add your handling code here:
       if(isSelectedInContainer)
       {
           if(sttDislay==1)
           {
               File f ;
                if(!isProcessSearch)
                {
                    Album alb=arrAlbum.get(iSelectedAlbum);
                    f = new File(alb.getFiles().get(imageChoosen).toString());
                }
                else
                {
                    f = lstImageForSearch.get(imageChoosen);
                }
                if(f.exists())
                {
                    ImageIcon imgOriginal = new ImageIcon(f.getPath());
                    Image a = imgOriginal.getImage();

                    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                    ImageSelection selection = new ImageSelection(a);
                    clipboard.setContents(selection, null);
                    pathForCopy=f;
                }
                
            
           }
           else
           {
               File f ;
                if(!isProcessSearch)
                {
                    Album alb=arrAlbum.get(iSelectedAlbum);
                    f = new File(alb.getFiles().get(imageChoosen).toString());
                }
                else
                {
                    f = lstImageForSearch.get(imageChoosen);
                }
                if(f.exists())
                {
                    ImageIcon imgOriginal = new ImageIcon(f.getPath());
                    Image a = imgOriginal.getImage();

                    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                    ImageSelection selection = new ImageSelection(a);
                    clipboard.setContents(selection, null);
                    pathForCopy=f;
                }
           }
            
       }
    }//GEN-LAST:event_menuCopyActionPerformed

    private void menuCutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCutActionPerformed
        // TODO add your handling code here:
        System.out.println("Alo11111111111111111111111111111");
    }//GEN-LAST:event_menuCutActionPerformed

    private void menuPasteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuPasteActionPerformed
        // TODO add your handling code here:
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
                            .getContents(null);
        if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
        try {
            Image img = (Image) t.getTransferData(DataFlavor.imageFlavor);
            
            BufferedImage bi = imageHelper.toBufferedImage(img);
            int n=0;
            JPanel pn=viewFolder;
            if(sttDislay==1)
            {
                TreePath selectedPath = Otree.getSelectionPath() ;
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
                File folder=(File)node.getUserObject();
                String fileName=folder.getAbsolutePath()+"\\"+pathForCopy.getName();
                File f=new File(fileName);
                if(f.exists())
                {
                    System.out.println("File da ton tai");
                }
                else
                {
                    String strName=f.getAbsolutePath();
                    int index1=strName.lastIndexOf(".");
                    String eFile=strName.substring(index1,strName.length());
                    ImageIO.write(bi, eFile, f);
                }   
                lstImageForfolder.add(pathForCopy);
                n=lstImageForfolder.size()-1;
                
            }
            else
            {
                int []i=OtreeAlbum.getSelectionRows();
                if(i.length>0 && i[0]>0)
                {
                    Album abl=arrAlbum.get(i[0]-1);
                    
                    String pathAlbum=getClass().getResource(fileAlbum).getPath();
                    process_XML.AddImageXML(pathAlbum,abl.getName(),pathForCopy.getAbsolutePath());
                    abl.getFiles().add(pathForCopy.getAbsolutePath());
                    //ResetImageForAlbum(abl);
                    iSelectedAlbum=i[0]-1;
                    n=abl.getFiles().size()-1;
                    pn=viewAlbum;
                }
            }
            
                
            ImageIcon imgOriginal=new ImageIcon(img);
            JLabel label=new JLabel("");
            label.setSize(150, 150);
            
            label.setName(Integer.toString(n));
            label.setHorizontalAlignment(JLabel.CENTER);
            ImageIcon ico=new ImageIcon(img);
            ico=imageHelper.imageSize(ico, label);
            label.setIcon(ico);
            int iRow=n/6;
            int iCol=n%6;
            label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
            label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
            label.addMouseListener(emf);

            
            pn.add(label);
            if(iCol==0)
                ResetView(n,pn);
            else
                pn.repaint();
        }
        
        catch (IOException ex) {
            Logger.getLogger(ViewPhotos.class.getName()).log(Level.SEVERE, null, ex);
        }   catch (UnsupportedFlavorException ex) {
                Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
            }
        
        }
                
    }//GEN-LAST:event_menuPasteActionPerformed

    private void menuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuExitActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_menuExitActionPerformed

    private void txtSearchMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtSearchMouseEntered
        // TODO add your handling code here:
        txtSearch.setFocusable(true);
    }//GEN-LAST:event_txtSearchMouseEntered

    private void viewSearchKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_viewSearchKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_viewSearchKeyPressed

    private void viewAlbumKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_viewAlbumKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode() == KeyEvent.VK_C)
            System.out.print("Zo roi");
    }//GEN-LAST:event_viewAlbumKeyPressed

    private void viewFolderKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_viewFolderKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode() == KeyEvent.VK_C)
            System.out.print("Zo roi1");
    }//GEN-LAST:event_viewFolderKeyPressed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        if(isSelectedInContainer)
        {
            if(sttDislay==1)
            {
                try{
 
    		File f;
                    if(!isProcessSearch)
                        f = lstImageForfolder.get(imageChoosen);
                    else
                        f = lstImageForSearch.get(imageChoosen);
 
    		if(f.delete()){
                    if(!isProcessSearch)
                    {
                        DeleteFile(viewFolder, lstImageForfolder,emf);
                    }
                    else
                    {
                         DeleteFile(viewSearch, lstImageForSearch,ems);
                    }
                }
                else{
    			System.out.println("Delete operation is failed.");
    		}
 
            }catch(Exception ex){
                System.out.println(ex.getMessage());
    	}
            }
            else
            {
                try{
                    String path="";
                    String pathAlbum=getClass().getResource(fileAlbum).getPath();
                    Album alb=arrAlbum.get(iSelectedAlbum);
                    if(!isProcessSearch)
                    {
                        path=alb.getFiles().get(imageChoosen).toString();
                        process_XML.RemoveImageXML(pathAlbum, alb.getName(), path);
                        alb.getFiles().remove(imageChoosen);
                        ResetImageForAlbum(alb);
                    }
                    else
                    {
                        File f = lstImageForSearch.get(imageChoosen);
                        path=f.getAbsolutePath();
                        process_XML.RemoveImageXML(pathAlbum, alb.getName(), path);
                        lstImageForSearch.remove(imageChoosen);
                        DeleteFile(viewSearch,lstImageForSearch,ems);
                    }
                    
                    
                
                
                TreePath selectedPath = OtreeAlbum.getSelectionPath() ;
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
                node.setUserObject(alb.getName()+" ("+alb.getFiles().size()+")");
 
            }catch(Exception ex){
 
    		ex.printStackTrace();
                
    	}
            }
        }
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void menuAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAboutActionPerformed
        // TODO add your handling code here:
   
        frmAboutUS f=new frmAboutUS(frmMain.this,true);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }//GEN-LAST:event_menuAboutActionPerformed

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        // TODO add your handling code here:
        ArrayList<String> arr=new ArrayList<String>();
        Album abl=new Album("", "", "", "", arr);
        NewAlbum na=new NewAlbum(this, true, abl);
        na.setVisible(true);
        if(!na.getIsClose())
        {
            arrAlbum.add(abl);
            ReloadPopupMenuForFolder();
            DefaultTreeModel model = (DefaultTreeModel) OtreeAlbum.getModel();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
            model.insertNodeInto(new DefaultMutableTreeNode(abl.getName()+" ("+abl.getFiles().size()+")"), root, root.getChildCount());
        }
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void search(File file,String filename) {
        if(!isRunnung)
            return;
	if (file.isDirectory() && file.getAbsolutePath().toLowerCase().contains("$RECYCLE.BIN".toLowerCase())==false) {
	  //System.out.println("Searching directory ... " + file.getAbsoluteFile());
 
            //do you have permission to read this directory?	
	    if (file.canRead()) {
		for (File temp : file.listFiles()) {
		    if (temp.isDirectory()) {
                        if(temp.getAbsolutePath().toLowerCase().contains("$RECYCLE.BIN".toLowerCase())==false)
                            search(temp,filename);
		    } else {
                        
			if (temp.getName().toLowerCase().contains(filename.toLowerCase())==true) {
                            Image image=isImage(temp.getPath());
                            
                            if(image!=null)
                            {
                                lstImageForSearch.add(temp);
                                
                                TotalSearched++;
                                
                                int n=lstImageForSearch.size()-1;
                                
                                ImageIcon imgOriginal=new ImageIcon(image);
                                JLabel label=new JLabel("");
                                label.setSize(150, 150);
                                label.setName(Integer.toString(n));
                                ImageIcon ico= imageHelper.imageSize(imgOriginal, label);
                                label.setHorizontalAlignment(JLabel.CENTER);
                                label.setIcon(ico);
                                int iRow=n/6;
                                int iCol=n%6;
                                label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                                label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
                                label.addMouseListener(ems);

                                viewSearch.add(label);
                                if(iCol==0)
                                    ResetView(n,viewSearch);
                                else
                                    viewSearch.repaint();
                                  
                            }
		    }
 
		}
	    }
 
	 } else {
		System.out.println(file.getAbsoluteFile() + "Permission Denied");
	 }
      }
 
  }

    public void StopActionSearch()
    {
        lbSearch.setText(" Total searched : "+TotalSearched);
        ResetView(lstImageForSearch.size()-1,viewSearch);
        jProgressBar1.setIndeterminate(false);
        String pathToImageSortBy = "images/Search.png";
        ImageIcon ico = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
        btnSearch.setIcon(ico);
        txtSearch.setEditable(true);
        txtSearch.setFocusable(true);
        isRunnung=false;
    }
    public void actionSearch_Folder() {
        SwingWorker worker;
        worker = new SwingWorker() {
            @Override
            public String doInBackground() {
                lstImageForSearch=new ArrayList<File>();
                jProgressBar1.setIndeterminate(true);
                viewSearch.removeAll();
                viewSearch.setVisible(true);
                isProcessSearch=true;
                viewFolder.setVisible(false);
                viewAlbum.setVisible(false);
                jScrollPane2.getViewport().add(viewSearch);
               
                TotalSearched=0;
                File[] roots = fileSystemView.getRoots();
                for(File fileSystemRoot : roots) {
                    fileSystemView = FileSystemView.getFileSystemView();
                    File[] files = fileSystemView.getFiles(fileSystemRoot, true);
                    for (File file : files) {
                        
                        if(file.isDirectory())
                        {
                            File[] Childfiles = fileSystemView.getFiles(file, true);
                            for (File Childfile : Childfiles) {
                                try
                                {
                                    if(!isRunnung)
                                    {
                                        StopActionSearch();
                                        return "stop";
                                    }
                                    search(new File(Childfile.getPath()),txtSearch.getText());
                                    lbSearch.setText("Searching in "+Childfile.getPath()+"  ...");
                                    Thread.sleep(100);
                                }
                                catch(Exception ex)
                                {
                                    System.out.println(ex.getMessage());
                                }
                             }
                        }
                    }
                }
                StopActionSearch();
                return "done";
            }
        };
        worker.execute();
    }
    
    public void actionSearch_Album(final String fileName) {
        SwingWorker worker;
        worker = new SwingWorker() {
            @Override
            public String doInBackground() {
                
                lstImageForSearch=new ArrayList<File>();
                arrAlbumNameForSearch=new ArrayList<String>();
                jProgressBar1.setIndeterminate(true);
                viewSearch.removeAll();
                
                viewSearch.setVisible(true);
                isProcessSearch=true;
                viewFolder.setVisible(false);
                viewAlbum.setVisible(false);
                jScrollPane2.getViewport().add(viewSearch);
                TotalSearched=0;
                int n=arrAlbum.size();
                for(int i=0;i<n;i++)
                {
                    Album abl=arrAlbum.get(i);
                    lbSearch.setText("Searching in "+abl.getName()+"  ...");
                    ArrayList<String>arrFile=abl.getFiles();
                    for(int j=0;j<arrFile.size();j++)
                    {
                        if(!isRunnung)
                        {
                            StopActionSearch();
                            return "stop";
                        }
                        File f=new File(arrFile.get(j));
                        if(f.exists())
                        {
                            if(f.getName().toLowerCase().contains(fileName.toLowerCase()))
                            {
                                TotalSearched++;
                                lstImageForSearch.add(f);
                                arrAlbumNameForSearch.add(abl.getName());
                                int n1=lstImageForSearch.size()-1;
                                
                                ImageIcon imgOriginal=new ImageIcon(f.getPath());
                                JLabel label=new JLabel("");
                                label.setSize(150, 150);
                                label.setName(Integer.toString(n1));
                                ImageIcon ico= imageHelper.imageSize(imgOriginal, label);
                                label.setHorizontalAlignment(JLabel.CENTER);
                                label.setIcon(ico);
                                int iRow=n1/6;
                                int iCol=n1%6;
                                label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY,1));
                                label.setBounds((iCol*175)+50,(iRow*175)+50, 150, 150);
                                label.addMouseListener(ems);

                                viewSearch.add(label);
                                if(iCol==0)
                                    ResetView(n1,viewSearch);
                                else
                                    viewSearch.repaint();
                            }
                        }
                    }
                }
                StopActionSearch();
                return "done";
            }
        };
        worker.execute();
    }
    
    
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmMain().setVisible(true);
                
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCaptureScreen;
    private org.jdesktop.swingx.JXButton btnNewAlbum;
    private org.jdesktop.swingx.JXButton btnSearch;
    private org.jdesktop.swingx.JXButton btnViewAlbum;
    private org.jdesktop.swingx.JXButton btnViewFiles;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu11;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator10;
    private javax.swing.JToolBar.Separator jSeparator11;
    private javax.swing.JToolBar.Separator jSeparator12;
    private javax.swing.JToolBar.Separator jSeparator13;
    private javax.swing.JToolBar.Separator jSeparator14;
    private javax.swing.JToolBar.Separator jSeparator15;
    private javax.swing.JToolBar.Separator jSeparator16;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar.Separator jSeparator9;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lbSearch;
    private javax.swing.JLabel lbStatusBar;
    private javax.swing.JMenuItem menuAbout;
    private javax.swing.JMenuItem menuCopy;
    private javax.swing.JMenuItem menuCut;
    private javax.swing.JMenuItem menuExit;
    private javax.swing.JMenuItem menuNewAlbum;
    private javax.swing.JMenuItem menuPaste;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JPanel viewAlbum;
    private javax.swing.JPanel viewFolder;
    private javax.swing.JPanel viewSearch;
    // End of variables declaration//GEN-END:variables
}
